import { Injectable } from "@angular/core";
import { filter } from "rxjs/operators";
import { Router, NavigationEnd, ActivationStart } from "@angular/router";
// import { MenuService } from '../layout/viewport/menu/menu.service';
import * as _ from "lodash";
import { UserProfileModel, AuthService } from "../auth/auth.service";

@Injectable()
export class UniversalService {
  static ROUTE_ACTIVATE = false;

  private routeHistory: Array<string> = new Array(10);

  /**
   * TODO: get version from package.json after v1.0.0 release
   */
  version = "alpha（内部测试版）";

  /* @tslint disable */
  info = `
        _    ____ ____ __   ____ ____ _      ____ __   ___  ____ ____ ____ ____ _
        || \\ |_ _\\|___\\| |  |___\\|_ _\\||_/\\  | . \\| |  |  \\ |_ _\\|  _\\|   || . \\|\\/\\
        ||_|\\  || | /  | |__| /    || | __/  | __/| |__| . \\  || | _\\ | . ||  <_|   \\
        |___/  |/ |/   |___/|/     |/ |/     |/   |___/|/\\_/  |/ |/   |___/|/\\_/|/v\\/

        %c信达基础支撑平台 - Utility Platform
        版本号: ${this.version}
        GIT: http://10.6.181.244/rd/utility-platform-web
        技术支持: 信达公司产品研发部
    `;

  constructor(private router: Router, private authService: AuthService) {
    this.bindMenuToRouter();
    this.printInfo();
  }

  private printInfo(): void {
    console.log(this.info, "padding-top: 5px;");
  }

  private bindMenuToRouter(): void {
    this.router.events
      .pipe(
        filter(
          event =>
            event instanceof ActivationStart || event instanceof NavigationEnd
        )
      )
      .subscribe((event: ActivationStart | NavigationEnd) => {
        if (event instanceof ActivationStart) {
          UniversalService.ROUTE_ACTIVATE = true;
        } else {
          this.pushRouteHistory(event.url);
          if (this.isLoggedIn()) {
            const menuList = this.authService.menuDataChanged.getValue();
            const activeMenu = _.chain(menuList)
              .filter(["href", event.url])
              .head()
              .value();
            if (activeMenu) {
              localStorage.setItem("nxszyMid", activeMenu.id);
              let topMenuId = _.chain(activeMenu.parentIds.split(","))
                .dropRight()
                .last()
                .value();
              if (!topMenuId) {
                topMenuId = activeMenu.id;
              }
              const activeTopMenu = _.chain(menuList)
                .filter(item => {
                  return (
                    item.id === topMenuId &&
                    (item.type === "1" || item.type === "2")
                  );
                })
                .head()
                .value();
              if (activeTopMenu.id != activeMenu.id) {
                activeTopMenu.activeMenuId = activeMenu.id;
              }
              this.authService.updateActiveTopMenu(activeTopMenu);
            }
          }
          UniversalService.ROUTE_ACTIVATE = false;
        }
      });
  }

  public getRouterHistory(): Array<string> {
    return _.chain(this.routeHistory)
      .clone()
      .reverse()
      .value();
  }

  public getPreviousRoute(): string {
    return _.first(this.getRouterHistory());
  }

  public pushRouteHistory(url: string): void {
    this.routeHistory = _.chain(this.routeHistory)
      .drop()
      .concat(url)
      .value();
  }

  public getUserName(): string {
    return this.getUserProfile() && this.getUserProfile().name;
  }

  public getUserImage(): string {
    return this.getUserProfile() && this.getUserProfile().image;
  }

  public isLoggedIn(): boolean {
    return (
      !!localStorage.getItem("token") && !!localStorage.getItem("userInfo")
    );
  }

  getUserProfile(): UserProfileModel {
    const profile = localStorage.getItem("userInfo");
    return profile ? JSON.parse(localStorage.getItem("userInfo")) : undefined;
  }
}
